package com.yizhang.annotation.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-06-10 17:52:26
 * @Description: mybatis配置类
 */
@Configuration
@EnableAspectJAutoProxy
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement
@MapperScan(basePackages = "com.yizhang.annotation.mapper")
public class MybatisConfiguration {

    @Bean
    public DataSource dataSource(@Value("${jdbc.driver}")String driver,
                                 @Value("${jdbc.url}")String url,
                                 @Value("${jdbc.username}")String username,
                                 @Value("${jdbc.password}")String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
